package com.cslc.wechat.faultreport.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.cslc.wechat.common.action.BaseAction;
import com.cslc.wechat.common.bean.Clerk;
import com.cslc.wechat.common.bean.Pending;
import com.cslc.wechat.common.bean.Terminal;
import com.cslc.wechat.common.dto.JsApiTicketInfo;
import com.cslc.wechat.common.mp.MpInfo;
import com.cslc.wechat.common.service.WechatService;
import com.cslc.wechat.faultreport.service.IFaultReportService;
import com.cslc.wechat.util.JsSignUtil;
import com.cslc.wechat.util.WeChatUtil;


public class FaultReportAction extends BaseAction{
	private static final long serialVersionUID = 4776450938698644215L;
	private static Logger logger = Logger.getLogger(FaultReportAction.class);
	private WechatService wechatService;
	private IFaultReportService faultReportService;
	private ArrayList<String> terminalNoArray; //绑定的终端编码数组
	private String tel; //手机号
	private String timestamp;
	private String nonceStr;
	private String signature;
	private String serverId; //图片id
	private String openid; //openid
	private String content; //事件的文字描述
	
	private String terminalNo; //用户选中的终端编码
	private String tagId; //用户选择的标签编号（有一定规则）

	/**
	 * 跳转到报障页面
	 */
	public String execute() throws Exception {
		HttpServletRequest request = this.request();
		HttpServletResponse response = this.response();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		//用户同意授权后获取code
		String code = request.getParameter("code");
		logger.info("code: " + code);
		//用户同意授权
		if(code != null && !"authdeny".equals(code)){
			JSONObject jsonObject = wechatService.getOauth2Acess(code);
			openid = jsonObject.getString("openid");
			logger.info("openid: " + openid);
			
			Clerk clerk = faultReportService.getClerkWithOpenid(openid);
			if(clerk != null) {
				//当前用户绑定的终端的set集合
				Set<Terminal> terminals = clerk.getTerminals();
				//已绑定过
				if(null != terminals && 0 < terminals.size()) {
					
					//设置手机号
					tel = clerk.getTel();
					//获取所有绑定终端的终端编码
					Iterator<Terminal> it = terminals.iterator();
					terminalNoArray = new ArrayList<String>();
					while (it.hasNext()) {
						terminalNoArray.add(it.next().getTerminalNo());
					}
					
					//验证获取jssdk权限，选择图片需用到jssdk
					JsApiTicketInfo jsapi_ticket  = WeChatUtil.getJsApiTicket();
					String url = MpInfo.HOST + "/faultReportMain?code=" + code + "&state=STATE";
					Map<String, String> ret = JsSignUtil.sign(jsapi_ticket.getTicket(), url);
					timestamp = ret.get("timestamp");
					nonceStr = ret.get("nonceStr");
					signature = ret.get("signature");
					logger.info("signature:" + signature);
					return SUCCESS;
				}
				else {
					return "unbind";
				}
			}
			//数据库中无该openid数据，关注未将用户数据插入
			return ERROR;
		}
		
		//授权失败
		else
			return ERROR;
	}
	
	public ArrayList<String> getTerminalNoArray() {
		return terminalNoArray;
	}

	public void setTerminalNoArray(ArrayList<String> terminalNoArray) {
		this.terminalNoArray = terminalNoArray;
	}

	public IFaultReportService getFaultReportService() {
		return faultReportService;
	}

	/**
	 * 在报障页面点击提交后增加报障信息
	 * @return
	 * @throws Exception
	 */
	public String faultReport() throws Exception {		
		logger.debug("openId:" + openid);
		logger.debug("serverId:" + serverId);
		logger.debug("content:" + content);
		logger.debug("terminalNo:" + terminalNo);
		logger.debug("tagId: " + tagId);
		
		String[] mediaIdStr = serverId.split(",");
		for(int i=0; i<mediaIdStr.length; i++) {
			wechatService.getTempMaterial(mediaIdStr[i]);
		}
		
		Pending pending = new Pending();
		pending.setOpenid(openid);
		pending.setTerminalNo(terminalNo);
		pending.setSerialNumber("20151201");
		pending.setMalfunctionType(tagId);
		pending.setText(content);
		pending.setImageId(mediaIdStr.toString());
		pending.setReportTime(new Date().toString());
		
		faultReportService.addPendingEvent(pending);
		
		return SUCCESS;
	}
	
	public String getTerminalNo() {
		return terminalNo;
	}

	public void setTerminalNo(String terminalNo) {
		this.terminalNo = terminalNo;
	}

	public String getTagId() {
		return tagId;
	}

	public void setTagId(String tagId) {
		this.tagId = tagId;
	}

	public void setFaultReportService(IFaultReportService faultReportService) {
		this.faultReportService = faultReportService;
	}
	
	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getSignature() {
		return signature;
	}

	public void setSignature(String signature) {
		this.signature = signature;
	}
	
	public String getNonceStr() {
		return nonceStr;
	}

	public void setNonceStr(String nonceStr) {
		this.nonceStr = nonceStr;
	}
	
	public String getOpenid() {
		return openid;
	}

	public void setOpenid(String openId) {
		this.openid = openId;
	}
	
	public String getServerId() {
		return serverId;
	}

	public void setServerId(String serverId) {
		this.serverId = serverId;
	}
	
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public WechatService getWechatService() {
		return wechatService;
	}

	public void setWechatService(WechatService wechatService) {
		this.wechatService = wechatService;
	}
	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}
}
